﻿using AutoMapper;
using B.S.Warehouse.Domain;
using B.S.Warehouse.ErrorCord;
using B.S.Warehouse.Read.Api.Application.Command.StockInApplicationcommands;
using MediatR;
using SqlSugar;

namespace B.S.Warehouse.Read.Api.Application.Handelr.StockInApplicationHandler
{
    public class GetStockInApplicationHandler : IRequestHandler<GetStockInApplicationCommand, ApiResult<ApiPaging<StockInApplication>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public GetStockInApplicationHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }
        public async Task<ApiResult<ApiPaging<StockInApplication>>> Handle(GetStockInApplicationCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<StockInApplication>> reat = new ApiResult<ApiPaging<StockInApplication>>();
            var listtt = await db.Queryable<StockInApplication>().Where(x => !x.IsDel).ToListAsync();


            if (!string.IsNullOrEmpty(request.DocumentSubject))
            {
                listtt = listtt.Where(x => x.DocumentSubject.Contains(request.DocumentSubject)).ToList();
            }
            if (!string.IsNullOrEmpty(request.DocumentNumber))
            {
                listtt = listtt.Where(x => x.DocumentNumber.Contains(request.DocumentNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.WarehouseKeeper))
            {
                listtt = listtt.Where(x => x.WarehouseKeeper.Contains(request.WarehouseKeeper)).ToList();
            }
            if (!string.IsNullOrEmpty(request.StockInCategory))
            {
                listtt = listtt.Where(x => x.StockInCategory.Contains(request.StockInCategory)).ToList();
            }
            if (request.ApplicationTime != null)
            {
                listtt = listtt.Where(x => x.ApplicationTime.Date == request.ApplicationTime.Value.Date).ToList();
            }
            int totalCount = listtt.Count();
            int PageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            listtt = listtt.OrderByDescending(a => a.Id).Skip((request.pageindex - 1) * request.pageSize).Take(request.pageSize).ToList();
            ApiPaging<StockInApplication> paging = new ApiPaging<StockInApplication>()
            {
                totalCount = totalCount,
                PageCount = PageCount,
                Result = listtt.ToList(),

            };

            reat.Code = ApiEnum.显示成功;
            reat.MAG = ApiEnum.显示成功.ToString();
            reat.data = paging;
            return reat;
        }
    }

}
